﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace LicPdaService
{
    public class PDAXmlOrderPickProcess
    {
        /// <summary>
        /// 3.1 PDA空箱扫描叫料 Add By Quinn.Ling 201703
        /// DataSource:Orders,OrdHistory,OrdHistoryDtl,PickDetail
        /// </summary>
        public static string GetPDAOrderPickData(XmlDocument doc)
        {
           
            #region 通用变量定义
            string docResult = string.Empty; //返回值
            string userid = string.Empty;
            string whseid = string.Empty;
            string requestshipdate=string.Empty;
            string orderkey = string.Empty;
            string sku = string.Empty;
            string customer_code = string.Empty;
            string label_qty = string.Empty;
            string return_status = "";
            string skudescr = string.Empty;
            string uom = string.Empty;
            string urgency = string.Empty;
            string box_num = string.Empty;
            string is_diaobo = string.Empty;
            List<string> sqllists = new List<string>();
            string strSql = string.Empty;
            string priority = "02";
            string type = "01";
           
            XmlDocument docreturn = new XmlDocument();//返回报文
            XmlDeclaration dec = docreturn.CreateXmlDeclaration("1.0", "utf-8", null);//建立Xml的定义声明  
            docreturn.AppendChild(dec);
            XmlElement rootResult = docreturn.CreateElement("NewDataSet"); //创建根节点
           
            #endregion

            try
            {
                #region 参数源
                //App.ws = new Fcl.WSOP.sqldbop();
                //App.ws.Init(System.Configuration.ConfigurationManager.ConnectionStrings["adpwmsConnectionString"].ConnectionString);
                XmlNode root = doc.DocumentElement; // 报文根节点
                XmlNodeList rootlist = root.ChildNodes;
                #endregion

                for (int i = 0; i < rootlist.Count; i++)
                {
                    #region 参数源
                    XmlNode nodeOrder = rootlist[i];
                    try
                    {
                        userid = nodeOrder.SelectSingleNode("userid").InnerText;
                        whseid = nodeOrder.SelectSingleNode("whseid").InnerText;
                        requestshipdate = nodeOrder.SelectSingleNode("requestshipdate").InnerText;
                        requestshipdate=requestshipdate.Replace("：", ":");
                        requestshipdate = requestshipdate + ":00";
                         sku = nodeOrder.SelectSingleNode("sku").InnerText;
                        label_qty = nodeOrder.SelectSingleNode("label_qty").InnerText;
                        try
                        {
                            urgency = nodeOrder.SelectSingleNode("urgency").InnerText;
                            box_num = nodeOrder.SelectSingleNode("box_num").InnerText;
                            is_diaobo= nodeOrder.SelectSingleNode("is_diaobo").InnerText;
                        }
                        catch { }

                        if (urgency.ToUpper()=="TRUE")
                        {
                            priority = "01";
                        }
                        if (is_diaobo.Trim()== "是")
                        {
                            type = "13";

                            
                        }
                        if (orderkey.Trim().Length <= 0)  //只有第一次循环时才生成出货单号
                        {
                            string lstype = "001";
                            if (whseid=="wh1")
                            {
                                lstype = "001";
                            }
                            else if (whseid=="wh2")
                            {
                                lstype = "019";
                            }
                            else if(whseid == "wh3") //新增wh3对应厂别代码 023
                            {
                                lstype = "023";
                            }
                            lstype = lstype + "OM";

                            strSql = "DECLARE @key varchar(50) exec pro_GetOrderNo '" + whseid + "','"+lstype+ "','OMORDERKEY','原料出货单号',@key OUTPUT select @key as orderkey";
                            DataTable dtOrd = App.GetDataTable(App.DBconWMS, strSql, "Sku");
                            if (dtOrd.Rows.Count > 0)
                            {
                                orderkey = dtOrd.Rows[0]["orderkey"].ToString();
                            }
                          
                        }

                        strSql = "SELECT description,unit,customer_code FROM Sku WHERE sku='" + sku + "' and whseid='"+whseid+"'";
                        DataTable dt = App.GetDataTable(App.DBconWMS, strSql, "Sku");
                        if (dt.Rows.Count > 0)
                        {
                            skudescr = dt.Rows[0]["description"].ToString();
                            uom = dt.Rows[0]["unit"].ToString();
                            customer_code = dt.Rows[0]["customer_code"].ToString();
                        }

                    }
                    catch (Exception ex) {
                        App.Log("PDAXmlOrderPickProcess.cs-3", ex.Message.ToString());
                    }
                    #endregion

                    #region 数据存储
                    try
                    {
                        sqllists.Clear();
                        //订单主档
                        strSql = "SELECT orderkey FROM Orders WHERE orderkey='"+ orderkey + "' AND customer_code='"+ customer_code + "'";
                        DataTable keydt = App.GetDataTable(App.DBconWMS, strSql, "Sku");
                        if (keydt.Rows.Count <= 0)
                        {
                            strSql = "insert into orders(whseid,orderkey,customer_code,external_orderno,delivery_order,consigneekey,status,type,priority,";
                            strSql += "waybill_no,transport_mode,delivery_terms,ship_name,voyage_no,self_delivery,data_from,requestshipdate,actshipdate,grossweight";
                            strSql += ",netweight,cube,plt,ctn,pcs,driver,truck_no,phone,udf1,udf2,udf3,udf4,remark,product,addwho,adddate,editwho,editdate) values ";
                            strSql += "('" + whseid + "','" + orderkey + "','" + customer_code + "','','','','01','"+ type + "','" + priority+ "'";
                            strSql += ",'','','','','','','PDA新增','" + requestshipdate + "','" + requestshipdate + "', 0";
                            strSql += ",0,0,0,0,0,'','','','','','','','','0','" + userid + "','" + DateTime.Now.ToString() + "','" + userid + "','" + DateTime.Now.ToString() + "')";
                            sqllists.Add(strSql);
                            //订单历史
                            strSql = "insert into OrdHistory(whseid,orderkey,status,operation,addwho,adddate) values ";
                            strSql += "('" + whseid + "','" + orderkey + "','01','新增PDA出货单','" + userid + "','" + DateTime.Now + "')";
                            sqllists.Add(strSql);
                        }


                     

                        //订单明细
                        string line_no = App.getOrderRowNo("orderdetail", "orderkey", whseid, orderkey);//获取行号
                        strSql = "insert into orderdetail(whseid,orderkey,line_no,customer_code,sku,skudescr,status,pre_qty,order_qty,act_qty,allocated_qty,picked_qty,unshiped_qty,";
                        strSql += " lottable01,lottable02,lottable03,lottable04,lottable05,lottable06,lottable07,lottable08,lottable09,lottable10";
                        strSql += ",uom,viceuom,udf1,udf2,udf3,udf4,remark,addwho,adddate,editwho,editdate,box_num) values ";
                        strSql += "('" + whseid + "','" + orderkey + "','" + line_no + "','" + customer_code + "','" + sku + "','" + skudescr + "','01'," + label_qty + "," + label_qty + ",0,0,0," + label_qty + "";
                        strSql += ",'','','','','','','','','',''";
                        strSql += ",'','','','','','','','" + userid + "','" + DateTime.Now.ToString() + "','" + userid + "','" + DateTime.Now.ToString() + "',"+box_num+")";
                        sqllists.Add(strSql);
                      
                        App.ExecuteSQLScriptLists(sqllists,App.DBconWMS);
                    }
                    catch (Exception ex)
                    {
                        return_status = "数据更新失败" + ex.Message.ToString();
                        string lerr_sql="";
                        for (int lni = 0; lni < sqllists.Count; lni++)
                        {
                            lerr_sql += "/";
                            lerr_sql += sqllists[lni].ToString();
                        }
                        App.Log("PDAXmlOrderPickProcess.cs-2", ex.Message.ToString()+"SQL:"+lerr_sql);
                    }
                    #endregion
                }

                #region 构建XML报文
                XmlNode order_result = docreturn.CreateElement("order_return");

                XmlElement useridResult = docreturn.CreateElement("userid");
                useridResult.InnerText = userid;
                order_result.AppendChild(useridResult);

                XmlElement whseidResult = docreturn.CreateElement("whseid");
                whseidResult.InnerText = whseid;
                order_result.AppendChild(whseidResult);

                XmlElement orderkeyResult = docreturn.CreateElement("orderkey");
                orderkeyResult.InnerText = orderkey;
                order_result.AppendChild(orderkeyResult);

                XmlElement return_statusResult = docreturn.CreateElement("return_status");
                return_statusResult.InnerText = return_status;
                order_result.AppendChild(return_statusResult);
               
                rootResult.AppendChild(order_result);
                #endregion

            }
            catch (Exception ex)
            {
                App.Log("PDAXmlOrderPickProcess.cs-1", ex.Message.ToString());
                //throw new Exception("异常源：PDAXmlOrderPickProcess:GetPDAOrderPickData;" + "  " + ex.Message);
            }

            docreturn.AppendChild(rootResult);
            return docreturn.InnerXml;
        }
    }
}
